package com.chromatic.competition.view.recruitment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chromatic.competition.R;
import com.chromatic.competition.adapter.PostListAdapter;
import com.chromatic.competition.model.UserPost;
import com.chromatic.competition.inteface.DatabaseCallback;
import com.chromatic.competition.utils.DatabaseHelper;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class RecruitmentFragment extends Fragment {
    private RecyclerView recyclerView;
    private PostListAdapter adapter;
    private SwipeRefreshLayout swipeRefreshLayout;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
        recyclerView = view.findViewById(R.id.recyclerView);
        swipeRefreshLayout = view.findViewById(R.id.swipeRefreshLayout);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        // 设置下拉刷新的颜色
//        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);

        // 设置下拉刷新的监听器
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // 执行刷新操作
                refreshData();
            }
        });

        // 获取从数据库中读取的数据列表
        getPostsFromDatabase(new DatabaseCallback() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onPostsLoaded(List<UserPost> userPostList) {
                // 在主线程更新 UI，将数据设置给适配器
                if (userPostList != null) {
                    requireActivity().runOnUiThread(() -> {
                        // 创建适配器并设置给RecyclerView
                        if (adapter == null) {
                            adapter = new PostListAdapter(userPostList);
                            recyclerView.setAdapter(adapter);
                        } else {
                            // Update adapter if already created
                            adapter.setPosts(userPostList);
                            adapter.notifyDataSetChanged();
                        }

                        // 停止下拉刷新动画
                        swipeRefreshLayout.setRefreshing(false);
                    });
                }
            }

            @Override
            public void onDatabaseError(Exception e) {
                // 在主线程处理数据库错误
                e.printStackTrace();

                // 停止下拉刷新动画
                swipeRefreshLayout.setRefreshing(false);
            }
        });

        ImageView sideBarButton = view.findViewById(R.id.sideBarButton);
        final LinearLayout sideBarLayout = view.findViewById(R.id.sideBarLayout);

        sideBarButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 切换侧边栏的可见性
                if (sideBarLayout.getVisibility() == View.GONE) {
                    sideBarLayout.setVisibility(View.VISIBLE);
                } else {
                    sideBarLayout.setVisibility(View.GONE);
                }
            }
        });

        ImageView gotoPostButton = view.findViewById(R.id.postButton);
        gotoPostButton.setOnClickListener(v -> {
            // 跳转到 LoginActivity
            Intent intent = new Intent(getActivity(), PostActivity.class);
            startActivity(intent);
        });

        return view;
    }

    private void getPostsFromDatabase(DatabaseCallback callback) {
        new Thread(() -> {
            Connection connection = null;
            Statement statement = null;
            ResultSet resultSet = null;
            List<UserPost> userPostList = new ArrayList<>();

            try {
                // 连接到数据库
                connection = DatabaseHelper.connect();

                // 创建并执行查询语句
                statement = connection.createStatement();
                String query = "SELECT * FROM user_post ORDER BY post_time DESC"; // 按发布时间逆序排序
                resultSet = statement.executeQuery(query);

                // 解析查询结果
                while (resultSet.next()) {
                    int userId = resultSet.getInt("user_id");
                    String category = resultSet.getString("category");
                    String competitionName = resultSet.getString("competition_name");
                    String postContent = resultSet.getString("post_content");
                    String postTime = resultSet.getString("post_time");
                    String startTime = resultSet.getString("start_time");
                    String endTime = resultSet.getString("end_time");
                    double expense = resultSet.getDouble("expense");
                    boolean isExpired = resultSet.getBoolean("is_expired");

                    // 创建 Post 对象并添加到列表中
                    UserPost userPost = new UserPost(userId, category, competitionName, postContent, postTime, startTime, endTime, expense, isExpired);
                    userPostList.add(userPost);
//                    Log.d("获取用户发帖数据成功，内容如下", postContent);
                }

                // 通知回调接口查询结果
                callback.onPostsLoaded(userPostList);
            } catch (SQLException e) {
                e.printStackTrace();
                // 通知回调接口数据库错误
                callback.onDatabaseError(e);
            } finally {
                // 关闭数据库连接和资源
                DatabaseHelper.close(resultSet);
                DatabaseHelper.close(statement);
                DatabaseHelper.close(connection);
            }
        }).start();
    }

    private void refreshData() {
        // 获取从数据库中读取的数据列表
        getPostsFromDatabase(new DatabaseCallback() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onPostsLoaded(List<UserPost> userPostList) {
                // 在主线程更新 UI，将数据设置给适配器
                if (userPostList != null) {
                    requireActivity().runOnUiThread(() -> {
                        // 创建适配器并设置给RecyclerView
                        if (adapter == null) {
                            adapter = new PostListAdapter(userPostList);
                            recyclerView.setAdapter(adapter);
                        } else {
                            // Update adapter if already created
                            adapter.setPosts(userPostList);
                            adapter.notifyDataSetChanged();
                        }

                        // 停止下拉刷新动画
                        swipeRefreshLayout.setRefreshing(false);
                    });
                }
            }

            @Override
            public void onDatabaseError(Exception e) {
                // 在主线程处理数据库错误
                e.printStackTrace();

                // 停止下拉刷新动画
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }
}